<?php
namespace apiadmin\modules\v1\controllers\trade;


use apiadmin\modules\v1\controllers\CoreController;
use common\bonus\SpeedBonus;
use common\models\GroupDetail;
use common\models\TradeCommodity;
use common\models\TradeSpeedBonus;

class CommodityController extends CoreController {

    public function actionListInfo()
    {

        $where  = $this->formartWhere();

        $params = array(
            'field'	=> ['*'],
            'order' => 'create_time desc',
            'page'	=> $this->request('page','1'),
            'limit' => $this->request('page_size',10),
        );
        $where['where']['type']=2;
        $list =TradeCommodity::dataList($where,$params);
        $pages = GroupDetail::$pages;
        $this->out('列表',$list,array('pages'=>$pages));
    }


    //组装条件
    public function formartWhere()
    {
        $where = [];
        $whereAnd = [];
        $searchKeys = json_decode($this->request('search'),1);

        if(!$searchKeys) return array('where'=>$where,'whereAnd'=>$whereAnd);
        foreach($searchKeys as $k=>$val)
        {
            if(!$val) continue;
            if($k=='date')
            {
                if(!$val['0'] || !$val['1']) continue;
                $whereAnd[] = ['between', 'create_time', date('Y-m-d',strtotime($val[0])),date('Y-m-d',strtotime($val[1]))];
            }elseif ($k=='member_name') {
                $whereAnd[] = ['like',$k,$val];
            }else
            {
                $where[$k] = $val;
            }
        }

        return array('where'=>$where,'and'=>$whereAnd);
    }

    public function actionInfo()
    {
        if(!$id = $this->request('commodity_id')) $this->error('参数错误');
        $data = TradeCommodity::getOne(['commodity_id'=>$id]);
        $this->out('拼团活动:'.$id,$data);
    }

    public function actionSave(){
        $model = new TradeCommodity;
        if($id = $this->request('commodity_id'))
            $model = TradeCommodity::findOne($id);
        else
            $model->create_time = date('Y-m-d H:i:s',time());

        $data = $this->request;
        $model->update_time = date('Y-m-d H:i:s',time());
        $model->type      =2;
        $model->finalist_income=0;
        if($model->load($data,'') && $model->save())
        {
            $this->out('操作成功');
        }

        $this->error('操作失败');
    }

    public function actionGetAlgebra(){
        $data = TradeSpeedBonus::getAll(['model_id'=>8]);

        foreach ($data as $k=>&$v) {
            $conditions=explode('and',$v['condition']);
            foreach ($conditions as $ck=>$cv){
                if (strstr($cv,'child_num')){
                    $child_num=explode('>=',$cv);
                    $v['child_num']=$child_num[1]?trim($child_num[1]):'';
                }elseif (strstr($cv,'pintuan '))
                {
                    $pintuan=explode('=',$cv);

                    $v['pintuan']=$pintuan[1]==1?true:false;
                }elseif (strstr($cv,'invest_money'))
                {
                    $invest_money=explode('>=',$cv);
                    $v['invest_money']=$invest_money[1]?trim($invest_money[1]):'';
                }
                unset($v['condition']);
            }
        }

        $this->out('投资列表代数设置',$data);
    }


    public function actionSetAlgebra(){
        $dataArr =$this->request;
        unset($dataArr['auth_key']);
        if (!$dataArr){
            return $this->error('请传数据');
        }
     $data = json_decode($dataArr['data'],true);

        foreach ($data as $k=>$v) {

            $dataInfo ['level']     =$v['level'];
            $dataInfo['rate']       = $v['rate'];
            $v['pintuan']=$v['pintuan']?1:0;
            if (!isset($v['invest_money'])){$v['invest_money']=0;}
            $dataInfo['condition'] = 'child_num >= ' . $v['child_num'] . ' and grade > 0 and pintuan = ' . $v['pintuan'].' and invest_money >= '.$v['invest_money']??0;
            $dataInfo['bonus_type'] =2;
            SpeedBonus::updateAll($dataInfo,'id='.$v['id']);
        }
        $this->out('操作成功');
    }


    public function actionSetDayIncome()
    {
        if(!$commodity_category = $this->request('commodity_category')) $this->error('参数错误');
        $val100 = $this->request('val100');
        $val200 = $this->request('val200');
        $val500 = $this->request('val500');
        $val1000 = $this->request('val1000');
        $val5000 = $this->request('val5000');
        try{
            $transaction = \Yii::$app->db->beginTransaction();
            if($val100){
                $model = TradeCommodity::find()->where(['commodity_category'=>$commodity_category, 'money_up'=>100])->all();
                foreach ($model as $commodity){
                    $commodity->day_income = $val100;
                    if(!$commodity->save()){
                        throw new \Exception('保存失败');
                    }
                }
            }
            if($val200){
                $model = TradeCommodity::find()->where(['commodity_category'=>$commodity_category, 'money_up'=>200])->all();
                foreach ($model as $commodity){
                    $commodity->day_income = $val200;
                    if(!$commodity->save()){
                        throw new \Exception('保存失败');
                    }
                }
            }
            if($val500){
                $model = TradeCommodity::find()->where(['commodity_category'=>$commodity_category, 'money_up'=>500])->all();
                foreach ($model as $commodity){
                    $commodity->day_income = $val500;
                    if(!$commodity->save()){
                        throw new \Exception('保存失败');
                    }
                }
            }
            if($val1000){
                $model = TradeCommodity::find()->where(['commodity_category'=>$commodity_category, 'money_up'=>1000])->all();
                foreach ($model as $commodity){
                    $commodity->day_income = $val1000;
                    if(!$commodity->save()){
                        throw new \Exception('保存失败');
                    }
                }
            }
            if($val5000){
                $model = TradeCommodity::find()->where(['commodity_category'=>$commodity_category, 'money_up'=>5000])->all();
                foreach ($model as $commodity){
                    $commodity->day_income = $val5000;
                    if(!$commodity->save()){
                        throw new \Exception('保存失败');
                    }
                }
            }
            $transaction->commit();
            $this->out('操作成功');
        }catch (\Exception $exception)
        {
            $transaction->rollback();
            $this->error($exception->getMessage().'('.$exception->getLine().')');
        }
    }
}